import React, {Component} from "react";
import MainItem from "../mainItem";
import PubSub from "pubsub-js";

export default class Main extends Component{
    //定义初始化数据
    state={mainList:[
            {id:'1',value:'吃饭',done:false},
            {id:'2',value:'睡觉',done:false},
            {id:'3',value:'敲代码',done:false}
        ]}

    //接受头部传参
    componentDidMount() {
        console.log('main挂载了')
      //新增表单项
      this.addMainItem=PubSub.subscribe('addMainItem',(_,mainObj)=>{
          let mainList=this.state.mainList
          this.setState({mainList:mainList.concat(mainObj)})
      })
        //删除所有已完成任务
        this.needDeleteDoneIds=PubSub.subscribe('needDeleteDoneIds',(_,needDeleteDoneIds)=> {
                this.handleDelete(needDeleteDoneIds)
            }
        )
        //全选或取消全选
        this.updateAllListDone=PubSub.subscribe('updateAllListDone',(_,updateInfo)=>{
            const {changeIds,checked}=updateInfo
            this.handleUpdate(changeIds,checked)
        })
    }

    //移除单项
    handleDelete=(ids)=>{
        let newMainList=this.state.mainList.filter(item=>!ids.includes(item.id))
        this.setState({mainList:newMainList})
    }

    //更新数据选中状态
    handleUpdate=(ids,done)=>{
        let newMainList=this.state.mainList.map(item=>{
            if(ids.includes(item.id)){
                return {...item,done:done}
            }else{
                return item
            }
        })
        this.setState({mainList:newMainList})
    }

    componentDidUpdate(prevProps: Readonly<P>, prevState: Readonly<S>, snapshot: SS) {
        PubSub.publish('updateMainList',this.state.mainList)
        console.log('mainList更新了',this.state.mainList)
    }
    //移除事件订阅
    componentWillUnmount() {
     PubSub.unsubscribe(this.addMainItem,this.needDeleteDoneIds,this.updateAllListDone)
  }
  //因为和mainItem是父子关系所以还是通过props传值
    render(){
       const {mainList}=this.state
        return (
            <ul className="todo-main">
                {mainList.map(mainItem=><MainItem {...mainItem} handleDelete={this.handleDelete} handleUpdate={this.handleUpdate} key={mainItem.id}></MainItem>)}
            </ul>
        )
    }

}
